package store

import (
	"github.com/fsnotify/fsnotify"
	"io/ioutil"
	"log"
	"os"
	"time"
)

// 监听操作系统 操作文件
func monitor() {

	// 创建文件/目录监听器
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer func(watcher *fsnotify.Watcher) {
		err := watcher.Close()
		if err != nil {
			log.Fatal(err)
		}
	}(watcher)

	done := make(chan bool)
	defer close(done)
	fileDone := make(chan bool)
	defer close(fileDone)
	go func() {
		ticker := time.NewTicker(50 * time.Millisecond)
		for range ticker.C {
			select {
			// 监听粒度较大(秒级) bug
			// 是否能支持cycle级别的文件监听
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				// 打印监听事件
				log.Println("event:", event)
			case _, ok := <-watcher.Errors:
				if !ok {
					return
				}
			}
		}
	}()
	// 监听当前目录
	err = watcher.Add("./")

	go func() {
		<-fileDone
		os.Remove("file_mode.txt")
		time.Sleep(1 * time.Second)
		done <- true
	}()
	go func() {
		data := []byte("update file content\n")
		// 覆盖式写入
		ioutil.WriteFile("file_mode.txt", data, 0664)
		time.Sleep(1 * time.Second)
		fileDone <- true
	}()
	<-done
}
